﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace RSSReader
{
    public partial class frmSetupUrl : Form
    {
        private List<RssChannel> _urlList = null;
        private int _interval = 0;
        private string _xmlFileName = "";

        public frmSetupUrl()
        {
            InitializeComponent();
            this.Icon = global::RSSReader.Properties.Resources.RSS_add;
        }

        public DialogResult SetupUrl(ref List<RssChannel> urlList, string xmlFileName, int interval)
        {
            _urlList = urlList;
            _xmlFileName = xmlFileName;
            _interval = interval;
            this.DialogResult = DialogResult.No;
            return this.ShowDialog();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string blogUrl = txtUrl.Text;

            if (txtUrl.Text == "")
            {
                MessageBox.Show("XML 주소를 입력하세요!", "블로그 추가 애러", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            else
            {
                Regex regPre = new Regex(@"([\w]+:)?//\w*");
                if (!regPre.Match(blogUrl).Success)
                {
                    blogUrl = "http://" + blogUrl;
                }

                // 다시 검사(RFC URL규정)
                Regex reg = new Regex(@"(([\w]+:)?//)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?");
                if (!reg.Match(blogUrl).Success)
                {
                    MessageBox.Show("XML 주소가 정확하지 않습니다!", "블로그 추가 애러", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    return;
                }
            }

            _urlList.Add(new RssChannel("", blogUrl));

            if (RSSFunctions.WriteDataXml(_urlList, _xmlFileName, _interval))
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
                txtUrl.Text = "";
            }
        }
    }
}